#pragma once

#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>

class ThreadPool {
public:
    explicit ThreadPool(size_t threads = 3) : stop{false} {
        for (size_t i = 0; i < threads; ++i)
            workers.emplace_back(
                    [this] {
                        while (true) {
                            std::function<void()> task;
                            {
                                std::unique_lock<std::mutex> lock(this->queue_mutex);
                                this->condition.wait(lock, [this] {
                                    return this->stop || !this->tasks.empty();
                                });
                                if (this->stop) return 0;
                                task = std::move(this->tasks.front());
                                this->tasks.pop();
                            }
                            task();
                        }
                    }
            );
    }

    template<class F, class... Args>
    auto commit(F &&f, Args &&... args) {
        auto task = std::make_shared<std::packaged_task<decltype(f(args...))()>>(
                std::bind(std::forward<F>(f), std::forward<Args>(args)...)
        );

        auto res = task->get_future();
        {
            std::lock_guard<std::mutex> lock(queue_mutex);
            tasks.emplace([task]() { (*task)(); });
        }
        condition.notify_one();
        return res;
    }

    void reset() {
        {
            std::lock_guard<std::mutex> lock(queue_mutex);
            stop = true;
        }

        condition.notify_all();
        for (std::thread &worker : workers)
            if (worker.joinable())
                if (worker.get_id() != std::this_thread::get_id()) {
                    worker.join();
                } else {
                    worker.detach();
                }

        std::lock_guard<std::mutex> lock(queue_mutex);
        stop = false;
    }

    ~ThreadPool() {
        reset();
    }

private:
    std::vector<std::thread> workers;
    std::queue<std::function<void()> > tasks;
    std::mutex queue_mutex;
    std::condition_variable condition;
    bool stop;
};